package com.yksj.healthtalk.ui.news;

import java.util.LinkedHashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;

import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.RootFragment;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.CoreService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.utils.SharePreUtils;
import com.yksj.healthtalk.utils.SystemUtils;
/**
 * 新闻主页
 * @author root
 *
 */
public class NewsMainFragment extends RootFragment implements OnCheckedChangeListener,OnClickListener {
	final LinkedHashMap<String,TableInfo> mTabMap = new LinkedHashMap<String,TableInfo>();
	RadioGroup mTabGroup;
	String mUserId; 
	JSONArray mTypeArray;
	String mCurrentTypeId;
	//默认图片
	FragmentManager mFragmentManager;
	BroadcastReceiver receiver=new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			 if(intent ==null )return;
			 //好评
			 if(CoreService.ACTION_COMMONT_CONTENT.equals(intent.getAction())){
					DoubleBtnFragmentDialog.showDefault(getChildFragmentManager(),"亲，您的好评是对我们最大的鼓励~", "下次吧", "鼓励一下",new OnDilaogClickListener() {
					@Override
					public void onDismiss(DialogFragment fragment) {
						SharePreUtils.updateCommentGoodDay();
					}
					@Override
					public void onClick(DialogFragment fragment, View v) {
						SharePreUtils.updateCommentGood();
						SystemUtils.commentGood(getActivity());
					}
				});
			}
		}
	};
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if(savedInstanceState != null){
			mCurrentTypeId = savedInstanceState.getString("id");
			if(savedInstanceState.containsKey("array")){
				String str = savedInstanceState.getString("array");
				try {
					mTypeArray = new JSONArray(str);
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		}
		mUserId = SmartFoxClient.getLoginUserId();
		mFragmentManager = getChildFragmentManager();
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view  = inflater.inflate(R.layout.news_tab_layout,null);
		mTabGroup = (RadioGroup)view.findViewById(R.id.radiogroup);
		mTabGroup.setOnCheckedChangeListener(this);
		
		initTitleView(view);
		
		titleLeftBtn.setOnClickListener(this);
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn2.setBackgroundResource(R.drawable.icon_wishlists);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleTextV.setText("健康要闻");
		return view;
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		if(mTypeArray == null){
			doQueryTypes();
		}else{
			doChangeTable(mCurrentTypeId);
		}
	}
	
	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		if(mTypeArray != null)outState.putString("array",mTypeArray.toString());
		if(mCurrentTypeId != null)outState.putString("id",mCurrentTypeId);
	}
	
	@Override
	public void onStart() {
		super.onStart();
		IntentFilter intentFilter=new IntentFilter();
		intentFilter.addAction(CoreService.ACTION_COMMONT_CONTENT);
		getActivity().registerReceiver(receiver, intentFilter);
	}
	
	@Override
	public void onStop() {
		super.onStop();
		getActivity().unregisterReceiver(receiver);
	}
	
	
	@Override
	public void onCheckedChanged(RadioGroup group, int checkedId) {
		View view = group.findViewById(checkedId);
		String  str = (String)view.getTag();
//		RadioButton button = (RadioButton)group.findViewById(checkedId);
//		titleTextV.setText(button.getText().toString());
		doChangeTable(str);
	}
	
	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back:
			onBackPressed(v);
			break;
		case R.id.title_right2:
			onCollectionClick();
			break;
		}
	}
	
	/**
	 * 收藏
	 */
	private void onCollectionClick(){
		Intent intent = new Intent(getActivity(),NewsCollectionActivity.class);
		startActivity(intent);
	}
	
	/**
	 * 查询新闻分类
	 */
	private void doQueryTypes(){
		HttpRestClient.doHttpQueryNewsTypes(mUserId,new JsonHttpResponseHandler(getActivity()){
			@Override
			public void onSuccess(int statusCode, JSONObject response) {
				super.onSuccess(statusCode, response);
			}
			@Override
			public void onSuccess(int statusCode, JSONArray response) {
				onParseTypeData(response);
			}
		});
	}
	
	/**
	 * 解析table数据
	 * @param jsonArray
	 */
	private void onParseTypeData(JSONArray array){
		LayoutInflater inflater = getLayoutInflater(null);
		for (int i = 0; i < array.length(); i++) {
			JSONObject jsonObject = array.optJSONObject(i);
			if(jsonObject == null)continue;
			String name = jsonObject.optString("MENUNAME");
			String code = jsonObject.optString("MENUCODE");
			RadioButton rb = (RadioButton)inflater.inflate(R.layout.news_radiobtn,null);
			rb.setText(name);
			rb.setTag(code);
			mTabGroup.addView(rb);
			TableInfo info = new TableInfo();
			info.bundle = new Bundle();
			info.bundle.putString("type",code);
			switch (i) {
			case 0:
				info.bundle.putInt("one",R.drawable.news1_yaowen1);
				info.bundle.putInt("two",R.drawable.news1_yaowen2);
				break;
			case 1:
				info.bundle.putInt("one",R.drawable.news2_jibing1);
				info.bundle.putInt("two",R.drawable.news2_jibing2);
				break;
			case 2:
				info.bundle.putInt("one",R.drawable.news3_xinli1);
				info.bundle.putInt("two",R.drawable.news3_xinli2);
				break;
			case 3:
				info.bundle.putInt("one",R.drawable.news4_kouqiang1);
				info.bundle.putInt("two",R.drawable.news4_kouqiang2);
				break;
			case 4:
				info.bundle.putInt("one",R.drawable.news5_yundong1);
				info.bundle.putInt("two",R.drawable.news5_yundong2);
				break;
			case 5:
				info.bundle.putInt("one",R.drawable.news6_meirong1);
				info.bundle.putInt("two",R.drawable.news6_meirong2);
				break;
			case 6:
				info.bundle.putInt("one",R.drawable.news7_xiuxian1);
				info.bundle.putInt("two",R.drawable.news7_xiuxian2);
				break;
			case 7:
				info.bundle.putInt("one",R.drawable.news8_yangsheng1);
				info.bundle.putInt("two",R.drawable.news8_yangsheng2);
				break;
			case 8:
				info.bundle.putInt("one",R.drawable.news9_jiankang1);
				info.bundle.putInt("two",R.drawable.news9_jiankang2);
				break;
			}
			info.className = NewsListFragment.class.getName();
			if(!mTabMap.containsKey(code)){
				mTabMap.put(code,info);
			}
		}
		int size = mTabGroup.getChildCount();
		if(size >0){
			RadioButton button = (RadioButton)mTabGroup.getChildAt(0);
			button.setChecked(true);
		}
	}
	
	private void doChangeTable(String id){
		FragmentManager fm = mFragmentManager;
		FragmentTransaction ft = fm.beginTransaction();
		TableInfo info = mTabMap.get(id);
		if(info == null) return;
		info.bundle.putString("title",titleTextV.getText().toString());
		TableInfo lastInfo = mTabMap.get(mCurrentTypeId);
		if(lastInfo != null && lastInfo.fragment != null){
			ft.detach(lastInfo.fragment);
		}
		if(info.fragment == null){
			Fragment fragment = Fragment.instantiate(getActivity(), info.className);
			fragment.setArguments(info.bundle);
			ft.add(R.id.fragmentcontent,fragment);
			info.fragment = fragment;
		}else{
			ft.attach(info.fragment);
		}
		ft.commitAllowingStateLoss();
		mCurrentTypeId = id;
	}
	
	/**
	 * 
	 * 获得最后一条的新闻id
	 * @return
	 * 
	 */
	public String getCurrentType(){
		TableInfo lastInfo = mTabMap.get(mCurrentTypeId);
		NewsListFragment fragment = (NewsListFragment)lastInfo.fragment;
		return fragment.type;
	}
	
	static class TableInfo{
		Bundle bundle;
		String className;
		Fragment fragment;
	}
	
}
